/*
 * =====================================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  05/21/2011 06:56:11 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Ken Chen (Ken), chen_kenz@emc.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include "timer_wheel.h"
#include "worker_queue.h"

static struct worker_queue wq;

int my_random(int high)
{
  return random() % high;
}

void timer_consumed_fun1(void *data)
{
  struct timer_entry* te = (struct timer_entry*)data;
  sleep(1);
  printf("timer_consumed_fun1\n");
  free(te);
}

void timer_consumed_fun2(void *data)
{
  struct timer_entry* te = (struct timer_entry*)data;
  sleep(1);
  printf("timer_consumed_fun2\n");
  free(te);
}

void timer_callback1(void* data)
{
  struct worker_entry* went = (struct worker_entry*)data;
  init_job(went, timer_consumed_fun1, data);
  add_job(&wq, went);
}

void timer_callback2(void* data)
{
  struct worker_entry* went = (struct worker_entry*)data;
  init_job(went, timer_consumed_fun2, data);
  add_job(&wq, went);
}

void* thrfunc_300(void* data)
{
	int st = 0;
  struct timer_entry* tim = NULL;
  for(;;)
  {
		st = my_random(300); 
    usleep(st*1000);
    tim = (struct timer_entry*)malloc(sizeof(struct timer_entry));
    init_timer(tim, timer_callback1, tim, 300);
    add_timer(tim);
		if(st&0x3)
		{
			usleep(100*1000);
      delete_timer(tim);
		}
  }
}

void* thrfunc_500(void* data)
{
	int st = 0;
  struct timer_entry* tim = NULL;
  for(;;)
  {
		st = my_random(500);
    usleep(st*1000);
    tim = (struct timer_entry*)malloc(sizeof(struct timer_entry));
    init_timer(tim, timer_callback2, tim, 500);
    add_timer(tim);
		if(st&0x3)
		{
			usleep(100*1000);
      delete_timer(tim);
		}
  }
}

void* worker_horse(void* data)
{
  do_jobs(&wq);
}

int main(int argc, char* argv[])
{
  pthread_t thr;
  srandom(time(NULL));
  init_timer_system();
  init_worker_queue(&wq);
  pthread_create(&thr, NULL, thrfunc_300, NULL);
  pthread_create(&thr, NULL, thrfunc_500, NULL);
  pthread_create(&thr, NULL, worker_horse, NULL);
  pthread_create(&thr, NULL, worker_horse, NULL);
  schedule_timers();
}

